<?php

namespace App\Http\Controllers\QRTerminal;

// use App\Models\Ad;
// use App\Models\AppLogo;
// use App\Models\User;
// use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Api\Controllers\Merchant\PayBaseController;
use App\Api\Controllers\Merchant\OrderController;
use App\Models\Device;

class BaseController extends \App\Api\Controllers\BaseController{
    
    // 表单提交字符集编码
    // public $postCharset = "UTF-8";
    // private $fileCharset = "UTF-8";
    // public $key = "88888888";
    // public $yhc_key = "FA217EE7D519894FD66BA660FFD3E5BE";
    // public $needpage = false; //默认不要分页

    // public $l = 15;
    // public $p = 1;
    // public $t = 0;

    // public $status = 1;
    // public $message = 'ok';
    
    // 获取签名
    function get_sign($value){
        // $data = $request->getContent(); // 获取传值

        // $data = explode("&", $data); // 字符串分割成数组
        
        // foreach($data as $k => $v){
        //     $key = explode("=", $v);
        //     $value[$key[0]] = $key[1];
        // }
        unset($value['sign']);
        // print_r($value);die;
        ksort($value); // 排序
        
        $sign = '';
        foreach($value as $k => $v){
            $sign .= $k . '=' . $v . '&';
        }
        
        $sign .= '8859a3725b1a67fb2767c1816c290d29'; // 串联成字符串（加上app_key）
        
        $sign = md5($sign); // md5加密
        $sign = strtoupper($sign); // 大写
        // print_r($sign);die;
        return $sign;
    }
    
    // 签名验证
    function sign_verify($data){
        $sign_old = $data['sign']; // 先把sign节点的值附值到其它变量
        unset($data['sign']); // 删除sign
        ksort($data); // 把数组按A-z排序
        
        $sign = '';
        foreach($data as $k => $v){ // 数组转字符串
            $sign .= $k . '=' . $v . '&';
        }
        // $sign .= 'GD1454DADAZX=DSAZZC4d55=='; // 串联成字符串（加上app_key）
        $sign .= '8859a3725b1a67fb2767c1816c290d29'; // 串联成字符串（加上app_key）
        $sign = md5($sign); // md5加密
        $sign = strtoupper($sign); // 大写
        
        if($sign != $sign_old){
            return json_encode([
                "code" => 400,
                "message" => "签名验证不通过",
                'data' => $sign_old
            ]);
        }
    }
    
    /**
     *  返回分页数据
    */
    public function page($obj, $request = '')
    {
        // print_r($request);die;
        if (empty($request))
            $request = app('request');

        $this->p = abs(trim($request->get('page_index', 1)));
        $this->l = abs(trim($request->get('page_size', 5)));

        $this->needpage = true;

        $start = abs(($this->p - 1) * $this->l);
        return $obj->offset($start)->limit($this->l);
    }
    
    /**
     * 校验必填字段
     */
    public function check_required($check, $data){
        $rules = [];
        $attributes = [];

        foreach ($data as $k => $v) {
            $rules[$k] = 'required';
            $attributes[$k] = $v;
        }
//        print_r($attributes);die;
        $messages = [
            'required' => ':attribute不能为空'
        ];
//        print_r($check);die;
        $validator = Validator::make($check, $rules, $messages, $attributes);
//
        $message = $validator->getMessageBag();
//        print_r($message);die;
        return $message->first();
    }
    
    //扫一扫收款
    public function scan_pay($data){
        try {
            $check_data = [
                'total_amount' => '付款金额',
                'code' => '付款码编号',
                'device_id' => '设备编号',
                'device_type' => '设备类型'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check
                ];
                return $this->return_data($err);
            }
            $code = $data['code'];
            $total_amount = $data['total_amount'];
            $shop_price = isset($data['shop_price']) ? $data['shop_price'] : $data['total_amount'];
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];
            $shop_name = isset($data['shop_name']) ? $data['shop_name'] : "扫一扫付款";
            $shop_desc = isset($data['shop_desc']) ? $data['shop_desc'] : "扫一扫付款";
            $other_no = isset($data['other_no']) ? $data['other_no'] : "";
            $qwx_no = isset($data['qwx_no']) ? $data['qwx_no'] : "";
            $remark = isset($data['remark']) ? $data['remark'] : "";
            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "0";
            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->select('merchant_id', 'merchant_name', 'store_id', 'config_id')
                        ->first();

                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定',
                        ];
                        return $err;
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $config_id = $Device->config_id;
                }


            }
            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'result_code' => '',
                'result_msg' => '',
                'other_no' => $other_no,
                'store_id' => $store_id,
                'ways_source' => '',
                'ways_source_desc' => '',
                'total_amount' => $total_amount,
            ];
            //请求参数
            $data = [
                'config_id' => $config_id,
                'merchant_id' => $merchant_id,
                'merchant_name' => $merchant_name,
                'code' => $code,
                'total_amount' => $total_amount,
                'shop_price' => $shop_price,
                'remark' => $remark,
                'device_id' => $device_id,
                'shop_name' => $shop_name,
                'shop_desc' => $shop_desc,
                'store_id' => $store_id,
                'other_no' => $other_no,
                'qwx_no' => $qwx_no,
            ];
            
            $pay_obj = new PayBaseController();
            $scan_pay_public = $pay_obj->scan_pay_public($data);
            $tra_data_arr = json_decode($scan_pay_public, true);
            // print_r($tra_data_arr);die;

            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message']
                ];
                return $err;
            }


            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {
                //微信，支付宝支付凭证
                $re_data['result_code'] = 'SUCCESS';
                $re_data['result_msg'] = '支付成功';
                $re_data['merchant_id'] = $merchant_id;
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['out_transaction_id'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['pay_time'] = date('Y-m-d H:i:s', strtotime(isset($tra_data_arr['data']['pay_time']) ? $tra_data_arr['data']['pay_time'] : time()));
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];
                
                
                
                // 诺诺开票
                $pay_obj = new PayBaseController();
                // $billing = '{"code":"E0000","describe":"同步成功","result":{"ewmUrl":"https://nnfp.jss.com.cn/invoice/scan/k.do?jc=MjA1NDA1MTA4MjA4MG5jbm5law==&on=NDA1MDA0ODA1MDA1MDA0OTA0ODA0OTA1MTA0OTA0OTA1MzA0ODA0OTA1MzA0OTA1NDA1NzA0ODA1NDA1MjA1N3hlZ3hleA==&flag=NTA5OTEwODEwNTEwMW1tZ21tcA=="}}';
                $billing = $pay_obj->billing($tra_data_arr['data']['out_trade_no']); // 开票地址
                $billing = json_decode($billing, true);
                
                if($billing['code'] == 'E0000'){
                    // print_r( $billing['result']['ewmUrl'] );die;
                    $re_data['invoice_url'] = $billing['result']['ewmUrl'];
                }
                // print_r($billing);die;
                
                // file_put_contents('1013.log', var_export($re_data, true) . "\r\n", FILE_APPEND);
                

                
                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }
                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }
                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }
                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }


            } elseif ($tra_data_arr['pay_status'] == '2') {
                //正在支付
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];
                $re_data['result_code'] = 'USERPAYING';
                $re_data['result_msg'] = '用户正在支付';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['total_amount'] = $tra_data_arr['data']['total_amount'];
                $re_data['merchant_id'] = $merchant_id;
            } else {
                //其他错误
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = $tra_data_arr['message'];
            }

            return $re_data;


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),
            ];
            return $err;
        }

    }
    
    //查询订单号状态
    public function order_query($data)
    {

        try {
            //获取请求参数
            //$data = $request->getContent();

            /*$data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }*/

            //  $other_no = isset($data['other_no']) ? $data['other_no'] : '';
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            /*$orderids = DB::table('orderids')->Where('out_trade_no', $out_trade_no)->first();
            if(!$orderids)
            {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '订单不存在',
                ];
                return $err;
            }else{
                $out_trade_no = $orderids->other_no;
            }*/

            // $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
            // $b = str_ireplace($a, "", $out_trade_no);
            // $day = substr($b, 0, 8);
            $table = 'orders';
            $orderdata = array();
            // if (Schema::hasTable($table)) {
            //     $orderdata = DB::table($table)->orWhere('out_trade_no', $out_trade_no)
            //         ->orWhere('trade_no', $out_trade_no)
            //         ->first();

            // } else {
            $orderdata = DB::table('orders')->orWhere('out_trade_no', $out_trade_no)->orWhere('trade_no', $out_trade_no)->orWhere('qwx_no', $out_trade_no)->orWhere('other_no', $out_trade_no)->first();
            if(!$orderdata){
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '订单号不存在',
                ];
                return $err;
            }
            // file_put_contents('1116.log', var_export($orderdata, true) . "\r\n", FILE_APPEND);
            // }
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];


            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";

            // 
            
            if ($orderdata->status == 6) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '已退款的交易，不能从这里发起查询！',
                ];
                return $err;
            }



            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';

            } else {

                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->first();

                    if (!$Device) {
                        // file_put_contents('1116.log', var_export(0, true) . "\r\n", FILE_APPEND);
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定',
                        ];
                        return $err;
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $store_name = $Device->store_name;
                    $config_id = $Device->config_id;
                }

            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'other_no' => $orderdata->other_no,
                'store_id' => $store_id,
            ];

            $order_foreach_public = [
                'out_trade_no' => $orderdata->out_trade_no,
                'store_id' => $orderdata->store_id,
                'ways_type' => $orderdata->ways_type,
                'config_id' => $orderdata->config_id,
                'table' => $table,
            ];

            $order_obj = new OrderController();
            $return = $order_obj->order_foreach_public($order_foreach_public);
            // file_put_contents('1116.log', var_export($return, true) . "\r\n", FILE_APPEND);
           // var_export($return);

            $tra_data_arr = json_decode($return, true);
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message'],
                ];
                return $err;
            }

            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {
                //微信，支付宝支付凭证
                $re_data['result_code'] = 'SUCCESS';
                $re_data['result_msg'] = '支付成功';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['out_transaction_id'] = $tra_data_arr['data']['out_trade_no'];
                //  $re_data['pay_time'] = date('Y-m-d H:i:s', strtotime($tra_data_arr['data']['pay_time']));
                $re_data['pay_time'] = $orderdata->pay_time;
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];
                $re_data['pay_amount'] = isset($tra_data_arr['data']['pay_amount']) ? $tra_data_arr['data']['pay_amount'] : "";
                $re_data['total_amount'] = isset($tra_data_arr['data']['total_amount']) ? $tra_data_arr['data']['total_amount'] : "";
                $re_data['other_no'] = isset($tra_data_arr['data']['other_no']) ? $tra_data_arr['data']['other_no'] : "";
                $re_data['status'] = $orderdata->status;
                $re_data['refund_time'] = $orderdata->updated_at;
                //
                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }
                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }
                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }
                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }


            } elseif ($tra_data_arr['pay_status'] == '2') {
                //正在支付
                $re_data['result_code'] = 'USERPAYING';
                $re_data['result_msg'] = '用户正在支付';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['total_amount'] = $tra_data_arr['data']['total_amount'];
            } else {
                //其他错误
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = $tra_data_arr['message'];
            }
            return $re_data;


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),];
            return $err;
        }


    }
    
    //退款查询接口
    public function refund_query($data)
    {
        try {

            $trade_no = isset($data['tade_no']) ? $data['tade_no'] : "";;
            $device_id = isset($data['device_id']) ? $data['device_id'] : "";
            $device_type = isset($data['device_type']) ? $data['device_type'] : "";
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            $refund_no = isset($data['refund_no']) ? $data['refund_no'] : "";

            $Device = Device::where('device_type', $device_type)
                // ->where('device_no', $device_id)
                ->where('id', $device_id)
                ->first();
            // print_r($device_type);
            // print_r($Device);die;
            if (!$Device) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '设备未绑定',
                ];
                return $err;
            }

            $store_id = $Device->store_id;

            /*
                        //查询表名
                        $orderids = DB::table('orderids')->Where('other_no', $trade_no)->first();
                        if (!$orderids) {
                            $err = [
                                'return_code' => 'FALL',
                                'return_msg' => '订单不存在',
                            ];
                            return $err;
                        } else {
                            $out_trade_no = $orderids->out_trade_no;
                        }*/

            $table = 'orders';

            $orderdata = array();
            // if (Schema::hasTable($table)) {
            //     $orderdata = DB::table($table)->orWhere('out_trade_no', $out_trade_no)
            //         ->orWhere('trade_no', $out_trade_no)
            //         ->first();

            // } else {
                $orderdata = DB::table('orders')->orWhere('out_trade_no', $out_trade_no)
                    ->orWhere('trade_no', $out_trade_no)->orWhere('qwx_no', $out_trade_no)
                    ->first();
            // }

            // var_export($orderdata);

            /*$RefundOrder = RefundOrder::where('store_id', $store_id)
                ->where('refund_no', $refund_no)
                ->select('refund_amount')
                ->first();*/

            if (!$orderdata) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '退款单号不存在',
                ];
                return $err;
            }


            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'result_code' => '',
                'result_msg' => '',
                'out_trade_no' => $out_trade_no,
                'trade_no' => $orderdata->trade_no,
                'time_end' => date("Y-m-d H:m:s", strtotime($orderdata->pay_time)),  //付款时间
                'total_fee' => $orderdata->total_amount,
                'refund_no' => $refund_no,
                'refund_amount' => $orderdata->shop_price,
                'pay_time' => $orderdata->updated_at,
                'ways_source' => $orderdata->ways_source,
                'ways_source_desc' => $orderdata->ways_source_desc,
                'status' => $orderdata->status,
                'store_name' => $orderdata->store_name,
                'merchant_name' => $orderdata->merchant_name,
            ];


            $re_data['result_code'] = 'SUCCESS';
            $re_data['result_msg'] = '退款成功';

            return $re_data;


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),
            ];
            return $err;
        }


    }
    
    //退款接口
    public function refund($data){
        try {
            //获取请求参数

            $device_id = isset($data['device_id']) ? $data['device_id'] : "";
            $device_type = isset($data['device_type']) ? $data['device_type'] : "";
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            $refund_amount = isset($data['refund_amount']) ? $data['refund_amount'] : "";
            $refund_no = isset($data['refund_no']) ? $data['refund_no'] : $out_trade_no . '123';


            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";


            $Device = Device::where('device_type', $device_type)
                ->where('device_no', $device_id)
                // ->where('id', $device_id)
                ->first();

            if (!$Device) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '设备未绑定',
                ];
                return $err;
            }

            $merchant_id = $Device->merchant_id;
            $merchant_name = $Device->merchant_name;
            $store_id = $Device->store_id;
            $config_id = $Device->config_id;


            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'result_code' => '',
                'result_msg' => '',
                'store_id' => $store_id,
                'out_trade_no' => $out_trade_no,
                'refund_amount' => $refund_amount,
            ];

            //请求参数
            $data = [
                'merchant_id' => $merchant_id,
                'out_trade_no' => $out_trade_no,
                'refund_amount' => $refund_amount,
                'refund_no' => $refund_no
            ];
            $pay_obj = new OrderController();
            $scan_pay_public = $pay_obj->refund_public($data);
            $tra_data_arr = json_decode($scan_pay_public, true);
            
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message']
                ];
                return $err;
            }else{
                //               echo '<pre>';
                // print_r($out_trade_no);
                // die;
                $order_obj = DB::table('orders')->orWhere('out_trade_no', $out_trade_no)->orWhere('trade_no', $out_trade_no)->orWhere('other_no', $out_trade_no)->first();
                
                if ($order_obj) {
                    $re_data['ways_source'] = $order_obj->ways_source ? $order_obj->ways_source : '';

                    if ($re_data['ways_source'] == 'alipay') {
                        $re_data['ways_source_desc'] = "支付宝";
                    }

                    if ($re_data['ways_source'] == 'weixin') {
                        $re_data['ways_source_desc'] = "微信支付";
                    }

                    if ($re_data['ways_source'] == 'jd') {
                        $re_data['ways_source_desc'] = "京东支付";
                    }

                    if ($re_data['ways_source'] == 'unionpay') {
                        $re_data['ways_source_desc'] = "银联";
                    }
                }
                $re_data['result_code'] = 'SUCCESS';
                $re_data['result_msg'] = '退款成功';
                
                return $re_data;
            }
            

        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),
            ];
            return $err;
        }


    }
}